<template>
  <el-card shadow="never" class="box">
    <template #header>
      <span class="title" style="font-size: 28px; font-weight: 700">药房发药</span>
    </template>

    <!-- 搜索 -->
    <el-card shadow="hover" class="search-card">
      <el-form :inline="true" onsubmit="return false">
        <el-form-item label="病历号">
          <el-input v-model="medicalNo" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 患者信息 -->
    <el-card shadow="hover" class="info-card" v-if="patient.caseNumber">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="姓名">{{ patient.realName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ patient.cardNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="家庭住址">{{ patient.homeAddress || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 处方列表 -->
    <el-card shadow="hover" class="consume-card" v-if="patient.caseNumber">
      <div class="table-title">患者处方列表</div>
      <!-- 当处方列表为空时显示提示 -->
      <div v-if="itemList.length === 0" class="empty-box">
        <div class="empty-text">该患者暂无处方记录</div>
      </div>
      <!-- 有数据时显示表格 -->
      <el-table 
        v-else
        :data="itemList" 
        stripe 
        border 
        size="small" 
        @selection-change="val => selectedRows = val"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="medicalNo" label="病历号" />
        <el-table-column prop="projectName" label="药品名称" />
        <el-table-column prop="unitPrice" label="单价" />
        <el-table-column prop="quantity" label="数量" />
        <el-table-column prop="createTime" label="开立时间" />
        
        <el-table-column label="发药状态">
          <template #default="{row}">
            <el-tag type="info">{{ row.dispenseStatus || '未知' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-bar" v-if="itemList.length > 0">
        <el-button type="primary" :disabled="selectedRows.length === 0" @click="handleDispense">发药</el-button>
      </div>
    </el-card>

    <!-- 空提示 -->
    <div v-else class="empty-box"><div class="empty-text">请输入病历号并搜索患者</div></div>
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

/* ---------- 数据 ---------- */
const medicalNo = ref('')
const patient = ref({
  caseNumber: '',
  realName: '',
  cardNumber: '',
  homeAddress: ''
})
const itemList = ref([])
const selectedRows = ref([])

/* ---------- 方法 ---------- */
const handleSearch = async () => {
  if (!medicalNo.value) return ElMessage.warning('请输入病历号')
  try {
    // 1. 重置状态（不变）
    patient.value = { caseNumber: '', realName: '', cardNumber: '', homeAddress: '' }
    itemList.value = []
    selectedRows.value = []

    // 2. 获取患者信息（不变，但要拿到 patientData.id）
    const { data: patientData } = await request.get(`/dispense/patient/${medicalNo.value}`)
    console.log('患者数据（含ID）：', patientData) // 确认有 id 字段（如 id=1）
    
    if (patientData && patientData.caseNumber && patientData.id) { // 新增判断 patientData.id
      patient.value = patientData
      ElMessage.success('查找成功')
      
      const { data: cRes } = await request.get(`/dispense/consume/${medicalNo.value}`)
// 如果是套壳：cRes.data 是数组；直接返回：cRes 就是数组
const list = Array.isArray(cRes) ? cRes : (cRes?.data || [])
itemList.value = list
console.log('处方数据：', list)
    } else {
      ElMessage.error('患者数据不完整（缺少ID）')
    }
  } catch (error) {
    console.error('搜索错误:', error)
    patient.value = { caseNumber: '', realName: '', cardNumber: '', homeAddress: '' }
    itemList.value = []
    selectedRows.value = []
    ElMessage.error('查找失败')
  }
}

const handleDispense = async () => {
  if (selectedRows.value.length === 0) return
  try {
    const ids = selectedRows.value.map(r => r.id)
    console.log('开始发药请求，IDs:', ids)
    
    // 直接获取响应（不依赖response.status）
    const response = await request.post('/dispense', ids)
    console.log('原始响应:', response)
    
    // 特殊处理：检查响应本身是否就是后端返回的data对象
    // 因为日志显示response直接是{code:200, message:...}
    const isSuccess = response && response.code === 200;
    
    if (isSuccess) {
      ElMessage.success(response.message || `发药成功，共 ${ids.length} 项`)
      handleSearch()
    } else {
      // 处理响应格式异常的情况
      console.error('响应格式异常:', response)
      ElMessage.error(response?.message || '发药失败：响应格式错误')
    }
  } catch (error) {
    console.error('捕获到异常:', error)
    
    // 检查异常中的code是否为200（应对拦截器错误处理）
    if (error && error.code === 200) {
      ElMessage.success(error.message || '发药成功')
      handleSearch()
    } else {
      let errorMsg = '网络错误'
      if (error?.message) {
        errorMsg = error.message
      }
      ElMessage.error(errorMsg)
    }
  }
}
     
    
    
</script>

<style scoped>
.box { padding: 0 20px 20px; }
.search-card,
.info-card,
.consume-card { margin-bottom: 16px; }
.table-title { margin-bottom: 8px; font-size: 16px; font-weight: 600; }
.footer-bar { display: flex; justify-content: center; margin-top: 24px; }
.empty-box { text-align: center; padding: 40px 0; font-size: 16px; color: #909399; }
</style>
    